package context.condition;

import cn.stimd.spring.context.annotation.Condition;
import cn.stimd.spring.context.annotation.ConditionContext;
import org.springframework.core.type.AnnotatedTypeMetadata;
import org.springframework.util.ClassUtils;
import org.springframework.util.MultiValueMap;

import java.util.List;

/**
 * Created by Stimd
 * 项目地址：https://gitee.com/stimd/spring-wheel
 * 公众号：Java编程探微
 */
public class MyOnBeanCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
        MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(MyConditionalOnBean.class.getName(), true);
        if (attrs != null) {
            for (Object value : attrs.get("value")) {
                if (value instanceof String[]) {
                    String[] arr = (String[]) value;
                    try {
                        Class<?> typeClass = ClassUtils.forName(arr[0], context.getClassLoader());
                        List<String> beanNames = context.getBeanFactory().getBeanNamesForType(typeClass);
                        if (!beanNames.isEmpty()) {
                            return true;
                        }
                    } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return false;
    }
}
